<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j addr-pop-con component-add-or-edit-address">
    <!-- 弹窗 -->
    <div class="popup-mask" />
    <div class="fix-transform-blur">
      <div class="popup-box">
        <!-- 新增地址 -->
        <div class="tit">
          <div
            v-if="editAddrId"
            class="text"
          >
            {{ $t('address.modifyAddress') }}
          </div>
          <div
            v-else
            class="text"
          >
            {{ $t('address.addRecipientInformation') }}
          </div>
          <div
            class="close"
            @click="hidePop"
          />
        </div>
        <div class="con">
          <div class="edit">
            <div class="item error">
              <div
                class="label"
                :class="['label',$t('language')==='en' ? 'labelEn' : '']"
              >
                <span class="asterisk">*</span>  {{ $t('address.recipient') }}：
              </div>
              <div class="text-box">
                <input
                  v-model="addressForm.receiver"
                  type="text"
                  class="input"
                  maxlength="15"
                  :placeholder="$t('address.recipientNameTips')"
                >
                <div
                  v-if="errTip===1"
                  class="error-text"
                >
                  {{ $t('address.recipientNameCannotBeEmpty') }}
                </div>
              </div>
            </div>
            <div class="item">
              <div :class="['label',$t('language')==='en' ? 'labelEn' : '']">
                <span class="asterisk">*</span> {{ $t('applyReturn.mobileNumber') }}：
              </div>
              <div class="text-box">
                <input
                  v-model="addressForm.mobile"
                  type="text"
                  class="input"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  maxlength="11"
                  :placeholder="$t('address.contactPhoneTips')"
                >
                <div
                  v-if="errTip===2"
                  class="error-text"
                >
                  {{ $t('address.cellPhoneNumberCannotBeEmpty') }}
                </div>
                <div
                  v-if="errTip===5"
                  class="error-text"
                >
                  {{ $t('address.cellPhoneNumberRightFormat') }}
                </div>
              </div>
            </div>
            <div class="item">
              <div :class="['label',$t('language')==='en' ? 'labelEn' : '']">
                <span class="asterisk">*</span>   {{ $t('freeShop.area') }}：
              </div>
              <div class="text-box">
                <div class="area-box">
                  <!-- 省 -->
                  <el-select
                    v-model="addressForm.province"
                    prop="province"
                    :placeholder="$t('applyReturn.select')"
                    class="area"
                    @change="selectProvince"
                  >
                    <el-option
                      v-for="province in provinceList"
                      :key="province.areaId"
                      :label="province.areaName"
                      :value="province"
                    >
                      {{ province.areaName }}
                    </el-option>
                  </el-select>
                  <!-- 市 -->
                  <el-select
                    v-model="addressForm.city"
                    prop="city"
                    class="area"
                    :placeholder="$t('applyReturn.select')"
                    @change="selectCity"
                  >
                    <el-option
                      v-for="city in cityList"
                      :key="city.areaId"
                      :label="city.areaName"
                      :value="city"
                    >
                      {{ city.areaName }}
                    </el-option>
                  </el-select>
                  <!-- 区 -->
                  <el-select
                    v-model="addressForm.area"
                    class="area"
                    prop="area"
                    :placeholder="$t('applyReturn.select')"
                    @change="selectArea"
                  >
                    <el-option
                      v-for="area in areaList"
                      :key="area.areaId"
                      :label="area.areaName"
                      :value="area"
                    >
                      {{ area.areaName }}
                    </el-option>
                  </el-select>
                </div>
                <div
                  v-if="errTip===3"
                  class="error-text"
                >
                  {{ $t('address.pleaseYourCompleteRegionalInformation') }}
                </div>
              </div>
            </div>
            <div class="item">
              <div :class="['label',$t('language')==='en' ? 'labelEn' : '']">
                <span class="asterisk">*</span>  {{ $t('freeShop.detailedAddress') }}：
              </div>
              <div class="text-box">
                <input
                  v-model="addressForm.addr"
                  type="text"
                  class="input"
                  maxlength="50"
                  :placeholder="$t('address.addressTips')"
                >
                <div
                  v-if="errTip===4"
                  class="error-text"
                >
                  {{ $t('freeShop.detailedAddressTips') }}
                </div>
              </div>
            </div>
            <div
              class="item item-btn"
              :style="{marginLeft:$t('language')==='en'?'35px':'0'}"
            >
              <div class="label-btn">
&nbsp;
              </div>
              <a
                href="javascript:void(0)"
                class="btn-r"
                @click="submitAddress"
              >{{ $t('address.saveRecipientInformation') }}</a>
            </div>
          </div>
        </div>
        <!-- /新增地址 -->
      </div>
    </div>
    <!-- /弹窗 -->
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  editAddrId: {
    type: String,
    default: null
  }
})
const emit = defineEmits(['getAddrList', 'toggleAddrPop', 'reloadOrderInfo', 'toggleAddrPop'])

const addressForm = ref({
  receiver: '', // 收货人
  mobile: '', // 手机号
  addr: '', // 详细地址
  addrId: 0, // 地址ID
  province: '',
  provinceId: null,
  postCode: '',
  city: '',
  cityId: null,
  area: '',
  areaId: null
})

onMounted(() => {
  init()
})

const provinceList = ref([])
// 页面加载获取数据:省份数据
const init = async () => {
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  // 等待地址信息返回
  if (props.editAddrId) {
    getAddrInfo(props.editAddrId)
  }
}

/**
 * 省市区
 */
const listAreaByParentId = (pid) => {
  let paramData
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http.get('/p/area/listByPid', {
    params: paramData
  })
}

// 获取地址列表
const getAreaListInfo = () => {
  return new Promise((resolve) => {
    http.get('/p/area/getAreaListInfo').then(({ data }) => {
      resolve(data)
    })
  })
}

const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}

const areaList = ref([])
const cityList = ref([])
/**
 * 选择省
 */
const selectProvince = (val) => {
  // 设置省id
  addressForm.value.provinceId = val.areaId
  addressForm.value.province = val.areaName
  // 将市和区的值清除
  addressForm.value.cityId = null
  addressForm.value.city = ''
  addressForm.value.areaId = null
  addressForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = getCurrentChild(provinceList.value, val.areaId)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val.areaId).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
/**
 * 选择市
 */
const selectCity = (val) => {
  // 设置市id
  addressForm.value.cityId = val.areaId
  addressForm.value.city = val.areaName
  // 将区域的值清除
  addressForm.value.areaId = null
  addressForm.value.area = ''
  // 获取区域的select
  const { curNode, areas } = getCurrentChild(cityList.value, val.areaId)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val.areaId).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}

/**
 * 选择区
 */
const selectArea = (val) => {
  // 设置区id
  addressForm.value.areaId = val.areaId
  addressForm.value.area = val.areaName
}

/**
 * 根据地址id获取地址信息
 */
const getAddrInfo = (addrId) => {
  http.get('/p/address/addrInfo/' + addrId).then(({ data }) => {
    if (data) {
      addressForm.value = data
      listAreaByParentId(data.provinceId).then(({ data }) => {
        cityList.value = data
      })
      listAreaByParentId(data.cityId).then(({ data }) => {
        areaList.value = data
      })
    }
  })
}

const errTip = ref(0) // 错误提示: 1-收件人 2-手机号 3-地区数据 4-详细地址
/**
 * 更新/添加地址
 */
const submitAddress = () => {
  if (!addressForm.value.receiver.trim()) {
    errTip.value = 1
    return
  } else if (!addressForm.value.mobile.trim()) {
    errTip.value = 2
    return
  } else if (!util.checkPhoneNumber(addressForm.value.mobile)) {
    errTip.value = 5
    return
  } else if (!addressForm.value.provinceId || !addressForm.value.cityId || !addressForm.value.areaId) {
    errTip.value = 3
    return
  } else if (!addressForm.value.addr.trim() || addressForm.value.addr.length < 5) {
    errTip.value = 4
    return
  } else {
    errTip.value = 0
  }
  const addrParam = {
    addrId: props.editAddrId ? props.editAddrId : 0,
    addr: addressForm.value.addr,
    area: addressForm.value.area,
    areaId: addressForm.value.areaId,
    city: addressForm.value.city,
    cityId: addressForm.value.cityId,
    mobile: addressForm.value.mobile,
    postCode: addressForm.value.postCode || '',
    province: addressForm.value.province,
    provinceId: addressForm.value.provinceId,
    receiver: addressForm.value.receiver
  }
  if (props.editAddrId) {
    addrParam.commonAddr = addressForm.value.commonAddr
  }
  http({
    method: props.editAddrId ? 'put' : 'post',
    url: props.editAddrId ? '/p/address/updateAddr' : '/p/address/addAddr',
    data: addrParam
  }).then(({ data }) => {
    ElMessage({
      message: data,
      type: 'success',
      duration: 1000
    })
    emit('getAddrList')
    emit('toggleAddrPop', false)
    emit('reloadOrderInfo')
  })
}

/**
 * 隐藏新增地址弹窗
 */
const hidePop = () => {
  emit('toggleAddrPop', false)
}

defineExpose({
  init,
  getAreaListInfo
})

</script>

<style lang="scss" scoped>
@use "index";
</style>
